package com.easyj.admin.configuration;

import java.util.TimeZone;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
/**
 * 对json（@RequestBody）参数的转换
 * @author hjf
 *
 */
@Configuration
public class MappingJackson2HttpMessageConverterConfig {

	@Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
		ObjectMapper objectMapper = new ObjectMapper();
        
		// 对于空的对象转json的时候不抛出错误
		//objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        
		// 禁用遇到未知属性抛出异常,否则如果@RequestBody传过json的属性多于bean的属性会报http 400 错误
		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		
		// 低层级配置
		//objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS,true);
		//objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true);
		//objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES,true);
		
		/**
		 * Jackson 默认使用ISO-8601，element日期时间使用也使用ISO-8601，不需要设置
		 * com.fasterxml.jackson.databind.util.StdDateFormat
		 * ISO-8601 compliant format (format String "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
		 */
		//objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); //统一日期格式Deserializer和Serialization
		//objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		//设置时区
		
		
		//[] >= null
		objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
		
		
		// ""=>null 以下自定义字符串处理已包含toNull
		//objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
				
        /**
           * 自定义字符串处理-：
          * 并对字符串 trim()，参数为true 则包含toNull
          * 一般 的字符串Field 都可以这样处理，
          * 有特别的，可加                         
         *   @JsonDeserialize(using = StringDeserializer.class)
                          *  使标准处理
         */
       SimpleModule module = new SimpleModule();
       module.addDeserializer(String.class, new StringBlanktoNullDeserializer(true));
       objectMapper.registerModule(module);
       return new MappingJackson2HttpMessageConverter(objectMapper);
	}
}
